
			
function htmlEncode(value){
	return $('<div/>').text(value).html();
}

// this function must be used for MySQL query return results.
function htmlDecode(value){
	return $('<div/>').html(value).text();
}	
			
// render a nebula
function render_nebula( nebula ) {
	var name       = nebula.name;
	var icon       = nebula.icon;
				
	var res = '<span><img src="' + icon + '" width="50" height="50" />' + name + '</span>';
				
	return res;
}

// render a group of nebulas as a table
function render_users( users ) {
	var header = '<table class="table" border="1"><tr><th>uid</th><th>avatar</th><th>group</th><th>username</th><th>email</th><th>ts</th></tr>';
	var res;
	res = header;
	for( var i = 0; i < users.length; i ++ ) {
		if( users[i].avatar == 0) {
			users[i].avatar = "img/noavatar_small.gif";
		}
		res += '<tr>';
		res += '<td>' + users[i].uid + '</td>';
		res += '<td><img width="50" height="50" src="' + users[i].avatar + '"/></td>';
		res += '<td>' + htmlDecode(users[i].group) + '</td>';
		res += '<td>' + htmlDecode(users[i].username) + '</td>';
		res += '<td>' + htmlDecode(users[i].email) + '</td>';
		res += '<td>' + users[i].ts + '</td>';
		res += '</tr>';
	}
	res += '</table> <br/>';
	res += 'A total of ' + users.length + " users.";
	return res;
}

function render_online_users( users ) {
	var header = '<table class="table" border="1"><tr><th>uid</th><th>avatar</th><th>username</th><th>last activity</th></tr>';
	var res;
	res = header;
	for( var i = 0; i < users.length; i ++ ) {
		if( users[i].avatar == 0) {
			users[i].avatar = "img/noavatar_small.gif";
		}
		res += '<tr>';
		res += '<td>' + users[i].uid + '</td>';
		res += '<td><img width="50" height="50" src="' + users[i].avatar + '"/></td>';
		res += '<td>' + htmlDecode(users[i].username) + '</td>';
		res += '<td>' + users[i].ts + '</td>';
		res += '</tr>';
	}
	res += '</table> <br/>';
	res += 'A total of ' + users.length + " users.";
	return res;
}
		
// render a group of nebulas as a table
function render_nebulas( nebulas ) {
	var header = '<table class="table" border="1"><tr><th>nid</th><th>icon</th><th>name</th><th>description</th><th>ts</th></tr>';
	var res;
	res = header;
	for( var i = 0; i < nebulas.length; i ++ ) {
		res += '<tr>';
		res += '<td>' + nebulas[i].nid + '</td>';
		res += '<td><img width="50" height="50" src="' + nebulas[i].icon + '"/></td>';
		res += '<td>' + htmlDecode(nebulas[i].name) + '</td>';
		res += '<td>' + htmlDecode(nebulas[i].description) + '</td>';
		res += '<td>' + nebulas[i].ts + '</td>';
		res += '</tr>';
	}
	res += '</table> <br/>';
	res += 'A total of ' + nebulas.length + " nebulas.";
	return res;
}

// render a group of nebulas as a table
function render_post_nebulas( nebulas ) {
	var header = '<table class="table" border="1"><tr><th>nid</th><th>icon</th><th>name</th></tr>';
	var res;
	res = header;
	for( var i = 0; i < nebulas.length; i ++ ) {
		res += '<tr>';
		res += '<td>' + nebulas[i].nid + '</td>';
		res += '<td><img width="50" height="50" src="' + nebulas[i].icon + '"/></td>';
		res += '<td>' + htmlDecode(nebulas[i].name) + '</td>';
		res += '</tr>';
	}
	res += '</table> <br/>';
	res += 'A total of ' + nebulas.length + " nebulas.";
	return res;
}

function render_user_nebulas( nebulas ) {
	var header = '<table border="1"><tr><th>unid</th> <th>nid</th> <th>icon</th> <th>name</th> <th>score</th> <th>count</th> <th>tag ts</th></tr>';
	var res;
	res = header;
	for( var i = 0; i < nebulas.length; i ++ ) {
		res += '<tr>';
		res += '<td>' + nebulas[i].unid + '</td>';
		res += '<td>' + nebulas[i].nid + '</td>';
		res += '<td><img width="50" height="50" src="' + nebulas[i].icon + '"/></td>';
		res += '<td>' + nebulas[i].name + '</td>';
		res += '<td>' + nebulas[i].score + '</td>';
		res += '<td>' + nebulas[i].count + '</td>';
		res += '<td>' + nebulas[i].ts + '</td>';
		res += '</tr>';
	}
	res += '</table> <br/>';
	res += 'A total of ' + nebulas.length + " nebulas.";
	return res;
}
// render a group of nebulas as a table
function render_galaxies( galaxies ) {
	var header = '<table border="1"><tr><th>gid</th><th>icon</th><th>title</th><th>creator uid</th><th>pids</th><th>nids</th><th>description</th><th>ts</th></tr>';
	var res;
	res = header;
	for( var i = 0; i < galaxies.length; i ++ ) {
		if( galaxies[i].pids == null ) {
			galaxies[i].pids = "";
		}
		if( galaxies[i].nids == null ) {
			galaxies[i].nids = "";
		}
		res += '<tr>';
		res += '<td>' + galaxies[i].gid + '</td>';
		res += '<td><img width="50" height="50" class="join-galaxy" gid="' + galaxies[i].gid + '" src="' + galaxies[i].icon + '"/></td>';
		res += '<td>' + galaxies[i].title + '</td>';
		res += '<td>' + galaxies[i].uid + '</td>';
		res += '<td>' + galaxies[i].pids + '</td>';
		res += '<td>' + galaxies[i].nids + '</td>';
		res += '<td>' + htmlDecode(galaxies[i].description) + '</td>';
		res += '<td>' + galaxies[i].gts + '</td>';
		res += '</tr>';
	}
	res += '</table>';
	return res;
}
// render a group of nebulas as a table
function render_user_galaxies( galaxies ) {
	var header = '<table border="1"><tr><th>gid</th><th>icon</th><th>title</th><th>pids</th><th>nids</th><th>join ts</th></tr>';
	var res;
	res = header;
	for( var i = 0; i < galaxies.length; i ++ ) {
		if( galaxies[i].pids == null ) {
			galaxies[i].pids = "";
		}
		if( galaxies[i].nids == null ) {
			galaxies[i].nids = "";
		}
		res += '<tr>';
		res += '<td>' + galaxies[i].gid + '</td>';
		res += '<td><img width="50" height="50" class="quit-galaxy" gid="' + galaxies[i].gid + '"src="' + galaxies[i].icon + '"/></td>';
		res += '<td>' + galaxies[i].title + '</td>';
		res += '<td>' + galaxies[i].pids + '</td>';
		res += '<td>' + galaxies[i].nids + '</td>';
		res += '<td>' + galaxies[i].cuts + '</td>';
		res += '</tr>';
	}
	res += '</table>';
	return res;
}


function show_all_users() {
	$('#all-users').html('<img src="img/wait.gif"/>');
	$.ziGET('all_users', {}, function(r) {
		var all_users = render_users( r );
		$('#all-users').html(all_users);
		$('#all-users').show("slow");
	} );	
}

function show_online_users() {
	$.ziGET('online_users', {}, function(r) {
		var users = render_online_users( r );
		$('#online-users').html(users);
	} );	
}

function update_all_nebulas() {
	$('#all-nebulas').html('<img src="img/wait.gif"/>');
	// show all nebulas in the wormhole system
	$.ziGET('all_nebulas', {}, function(r) {
		var all_nebulas = render_nebulas( r );
		$('#all-nebulas').html(all_nebulas);
		$('#all-nebulas').show("slow");
	} );
}
				
function update_my_nebulas() {
	$('#your-nebulas').html('<img src="img/wait.gif"/>');
	// show only your tagged nebulas
	$.ziGET('nebulas_for_uid', {
		uid: this_uid
	}, function(r) {
		$('#your-nebulas').html(render_user_nebulas(r));
		$('#your-nebulas').show("slow");
	});
}
function add_nebula() {
	if( $('#newnebula-name').val().length < 2 ) {
		alert("nebula name too short!(at least 4 characters)");
		return;
	}
			
	$.ziGET('add_nebula', 
	{
		'name': $('#newnebula-name').val(),
		'icon': $('#newnebula-icon').val(),
		'description': $('#newnebula-description').val()
	}, 
	function(r) {
		if( r > 0 )
			update_all_nebulas();
		else 
			alert( "nebula name already exists!" );
	} );
}

function add_circle() {
    var uid = $('#newfriend-uid').val();
    var nid = $('#newfriend-nid').val();
    $.ziGET('circle',{'uid_to':uid,'nid':nid},function(r){
        alert(r);
        if(r==1)
            alert('you have circled a friend');
        else
            alert('Something is wrong');
    });
}
function tag_nebula( tags ) {
	$.ziGET('tag_nebula', 
	{
		'tags': tags
	}, 
	function(r) {
		if( r > 0 ) {
			update_my_nebulas();
			$('#tag-nebula-nebulas').val("");
		}
	} );
}
		
		
function show_nebula_content( nid ) {
	$.ziGET('get_nebula_content', 
	{
		'nid': nid
	}, 
	function(r) {
		var container = $("#nebula_content");
		var html = '<div><p>';
		for( var i = 0; i < r.length; i ++) {
			var data = r[i].data;
			if( r[i].type == 'post' ) {
				html += "<div style='background-color: #aaaaff'><h4>" + data.title + "</h4><br/>posted at " + data.ts + " by <strong>" + data.username + "</strong></div>";
			} else {
				html += "<div style='background-color: #ffaaaa'><h4>" + data.title + "</h4><br/>created at " + data.ts + " by <strong>" + data.username + "</strong></div>" ;
			}
			html += "<br />";
		}
		html += '</p></div>';
		container.html( html );
	} );	
}		
		
function new_post( title, nebulas, body, callback ) {
	$.ziPOST('new_post', 
	{
		'title':   title,
		'nebulas': nebulas,
		'body':    body
	}, 
	function(r) {
		if( r > 0 ) {
			alert("Your post has been submitted!");
			callback();
		} else {
			alert("Check your input nebula names!");
		}
	} );
}
		
function show_posts( max_num ) {
	$('#posts-container').html('<img src="img/wait.gif"/>');
	if( max_num == undefined ) {
		max_num = 100;
	}
	$.ziGET('show_posts', 
	{
		'max_num': max_num
	}, 
	function(r) {
		if( r <= 0 ) {
			$('#posts-container').html("Error occured when trying to fetch posts from database");	
		} else {
			var content = "";
			for( var i = 0; i < r.length; i ++ ) {
				content += '<div style="background-color: rgba(255,238,187, 0.6)">';
				content += "<div class='post-title' pid='" + r[i].pid + "'><span class='title-score'><span class='post-rate' v='pos'>[+]</span><span class='post-rate' v='neg'>[-]</span></span>" + r[i].title + "</div>";
				content += "<span id='post-score'><h4>Total score: " + r[i].score.score + "</h4></span>";
				content += "<h4>pid: " + r[i].pid + "</h4>";
				content += '<h5 class="post-body">' + htmlDecode(r[i].body) + '</h5>';
				var nebulas = r[i].nebulas;
				content += "nebulas tagged by the author <br /> ";
				content += render_post_nebulas(nebulas);
				content += '<br />';
				content += 'posted by <strong>' + r[i].author.username + "</strong> on " + r[i].ts ;
				content += '</div>';
			}
			content += '<p>Total of ' + r.length + " posts" + '</p>';
			$('#posts-container').hide("slow");
			$('#posts-container').html(content);
			$('#posts-container').show("slow");
		}
	})
}
		
function add_galaxy( title, icon, decription, pids, nids, callback ) {
	if( decription == undefined || decription == "" ) {
		decription = '';
	}
	$.ziPOST('add_galaxy', 
	{
		'title':       title,
		'icon':        icon,
		'description': decription,
		'pids':        pids,
		'nids':	       nids
	}, 
	function(r) {
		alert(r);
		if( r > 0 ) {
			callback();
		} else {
			alert("Something is wrong when adding new galaxy");
		}
	} );
}
function tag_galaxy( gid, pids, nids, callback ) {
	$.ziPOST('tag_galaxy', 
	{
		'gid':   gid,
		'pids':  pids,
		'nids':	 nids
	}, 
	function(r) {
		if( r > 0 ) {
			callback();
		} else {
			alert("Something is wrong when tagging galaxy");
		}
	} );		
}

function show_galaxies() {
	$.ziGET('all_galaxies', 
	{}, 
		function(r) {
			$('#galaxy-container').html(render_galaxies(r));
			$('#galaxy-container').show("slow");
			$("img.join-galaxy").click(function() {
				$("#your-galaxy-container").hide("slow");
				join_galaxy($(this).attr("gid"), show_galaxies_for_uid );
			});
		}
	);
}

function show_galaxies_for_uid(selector, uid) {
	if(selector == undefined) selector = $("#your-galaxy-container");
	
	if(uid == undefined || uid == "") {
		uid = this_uid;
	}
	$.ziGET('galaxies_for_uid', 
	{
		'uid': uid
	}, 
	function(r) {
		selector.html(render_user_galaxies(r));
		selector.show("slow");
		$("img.quit-galaxy").click(function() {
			selector.hide("slow");
			quit_galaxy($(this).attr("gid"), show_galaxies_for_uid);
		});
	});		
}
function join_galaxy(gid, callback) {
	$.ziGET('join_galaxy', 
	{
		'gid': gid
	}, 
	function(r) {
		if( r > 0 )
			callback();
		else {
			$("#your-galaxy-container").show("slow");
		}
	});		
}
function quit_galaxy(gid, callback) {
	$.ziGET('quit_galaxy', 
	{
		'gid': gid
	}, 
	function(r) {
		if( r > 0 )
			callback();
		else {
			$("#your-galaxy-container").show("slow");
		}
	});		
}

function show_chat_for_gid (gid) {
	$.ziGET('getChats',
	{
		gid: gid
	},
	function(r) {
		
	});			
}

function add_chat_for_gid (gid, text, callback) {
	$.ziPOST('submitChat',
	{
		'gid': gid,
		'text': text
	},
	function(r) {
		if( r > 0 ) {
			callback();
		} else {
			alert("you have not joined this galaxy yet.");
		}
	});
}


function render_galaxy_chats( chats ) {
	var content = "<table><tr><th>icon</th><th>gid</th><th>title</th><th>avatar</th><th>username</th><th>text</th><th>ts</th></tr>";
	for( var i = 0; i < chats.length; i ++ ) {
		content += "<tr>";
		content += "<td><img width='50' src='" + chats[i].icon + "'/></td>";
		content += "<td>" + chats[i].gid + "</td>";
		content += "<td>" + chats[i].title + "</td>";
		content += "<td><img width='50' src='"  + chats[i].avatar + "'/></td>";
		content += "<td>" + chats[i].username + "</td>";
		content += "<td><strong>" + chats[i].text + "</strong></td>";
		content += "<td>" + chats[i].ts + "</td>";
		content += "</tr>";
	}
	content += "</table>";
	return content;
}

function show_galaxy_chats() {
	$.ziGET('getAllChats', 
	{}, 
		function(chats) {
			$('#galaxy-chats').html(render_galaxy_chats( chats ));
		}
	);	
}

function change_avatar( url, callback ) {
	$.ziPOST('updatefield', 
	{
		'field': 'avatar', 
		'newval': url
	},
	function(r) {
		if( r > 0 )
			callback();
		else
			alert("Something is wrong!");
	});			
}

function refresh_all( ) {
	show_all_users();
	show_online_users();
	update_all_nebulas();
	update_my_nebulas();
	show_posts();
	show_galaxies();
	show_galaxies_for_uid();
	show_galaxy_chats();
	show_nebula_content(4);
}
		
$(function() {
	refresh_all();
	setInterval( function() {
		show_galaxy_chats();
		show_online_users();
	}, 10000 );
	// -----------------------------------------------------------------
	// user mouse events:
			
	$('#newnebula-button').click( function() {
		add_nebula();
	});

    $('#newcircle-button').click(function(){
        add_circle();
    });
	$('#tag-nebula-button').click(			
		function(){
			if( $('#tag-nebula-nebulas').val().length < 2 )
				return;
			tag_nebula( $('#tag-nebula-nebulas').val() );
		}
		);
	$('#newpost-button').click(
		function(){
			new_post( $('#newpost-title').val(), $('#newpost-nebulas').val(), $('#newpost-body').val(), 
				function() {
					$('#newpost-title').val("");
					$('#newpost-nebulas').val("");
					$('#newpost-body').val("");
					show_posts();
				} );
		});
	$('#newgalaxy-button').click(
		function(){
			add_galaxy( 
				$('#newgalaxy-title').val(), 
				$('#newgalaxy-icon').val(), 
				$('#newgalaxy-description').val(), 
				$('#newgalaxy-pids').val(),
				$('#newgalaxy-nids').val(),
				function() {
					$('#newgalaxy-title').val("");
					$('#newgalaxy-icon').val("");
					$('#newgalaxy-description').val("");
					$('#newgalaxy-pids').val("");
					$('#newgalaxy-nids').val("");
					show_galaxies();
				} );
		});	
		
	$('#taggalaxy-button').click( 
		function() {
			tag_galaxy (
				$('#taggalaxy-gid').val(),
				$('#taggalaxy-pids').val(),
				$('#taggalaxy-nids').val(),
				function() {
					$('#taggalaxy-gid').val(""),
					$('#taggalaxy-pids').val(""),
					$('#taggalaxy-nids').val(""),
					show_galaxies();
				} 
				);
		}
		);
	$('#galaxy-join-button').click( function(){
		join_galaxy($("#galaxy-join-gid").val(), 
			function() {
				show_galaxies_for_uid($("#your-galaxy-container"));
				$("#galaxy-join-gid").val("");
			});
	});
	$('#galaxy-quit-button').click( function(){
		quit_galaxy($("#galaxy-quit-gid").val(), 
			function() {
				show_galaxies_for_uid($("#your-galaxy-container"));
				$("#galaxy-quit-gid").val("");
			});
	});
	$('#add-chat-button').click( function() {
		add_chat_for_gid( $("#add-chat-gid").val(), $('#add-chat-text').val(), show_galaxy_chats );
	});
	$('#user-avatar').click( function() {
		var avatar_url = prompt("Enter your desired avatar icon url:", $('#user-avatar').attr("src"));
		if(avatar_url == null) return;
		$('#user-avatar').attr("src", "img/wait.gif");
		change_avatar( avatar_url, function() {
			$('#user-avatar').attr("src", avatar_url);
		});
	});

});